package com.example.userlogin.config;

import com.example.userlogin.dto.SignupRequest;
import com.example.userlogin.service.UserService;
import com.example.userlogin.service.UserRegistrationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

/**
 * 数据初始化器
 * 职责：应用启动时初始化默认数据
 */
@Component
public class DataInitializer implements CommandLineRunner {

    @Autowired
    private UserService userService;

    @Autowired
    private UserRegistrationService userRegistrationService;

    @Override
    public void run(String... args) throws Exception {
        // 创建默认管理员用户
        createDefaultAdminUser();
        
        // 创建测试用户
        createDefaultTestUser();
    }

    private void createDefaultAdminUser() {
        if (!userService.existsByUsername("admin")) {
            try {
                SignupRequest adminRequest = new SignupRequest();
                adminRequest.setUsername("admin");
                adminRequest.setEmail("admin@example.com");
                adminRequest.setPassword("admin123");

                userRegistrationService.registerUser(adminRequest);
                
                System.out.println("默认管理员用户已创建:");
                System.out.println("用户名: admin");
                System.out.println("密码: admin123");
                System.out.println("邮箱: admin@example.com");
            } catch (Exception e) {
                System.err.println("创建管理员用户失败: " + e.getMessage());
            }
        }
    }

    private void createDefaultTestUser() {
        if (!userService.existsByUsername("testuser")) {
            try {
                SignupRequest testRequest = new SignupRequest();
                testRequest.setUsername("testuser");
                testRequest.setEmail("test@example.com");
                testRequest.setPassword("test123456");

                userRegistrationService.registerUser(testRequest);
                
                System.out.println("测试用户已创建:");
                System.out.println("用户名: testuser");
                System.out.println("密码: test123456");
                System.out.println("邮箱: test@example.com");
            } catch (Exception e) {
                System.err.println("创建测试用户失败: " + e.getMessage());
            }
        }
    }
}